package com.bps.zzant.json;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;



import org.springframework.util.StringUtils;

import com.bps.zzant.model.ToDo;
import com.bps.zzant.services.ToDoService;

@Controller
public class ToDoJSON {
	
	private static final Logger logger = LoggerFactory.getLogger(ToDoJSON.class);

	@Autowired
	private ToDoService toDoService;
	public void setToDoService(ToDoService toDoService) {
		this.toDoService = toDoService;
	}
	
   @InitBinder
   public void initBinder(WebDataBinder binder) {
           SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
           dateFormat.setLenient(false);
           binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
   }
	
	
	@RequestMapping(value = "getToDoList.json", method = RequestMethod.POST)
	public Map getToDoList(HttpServletRequest request, HttpServletResponse response) {
		// logger.info(" +++++++++in getToDoList.json . The owner is:"+ request.getParameter("owner"));
		logger.info(" +++++++++in getToDoList.json: status:"+ request.getParameter("status")+"|"+"owner:"+request.getParameter("owner")+"|"+request.getParameter("fromDate")+"|"+request.getParameter("toDate"));
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		String status = request.getParameter("status")==null?"open":request.getParameter("status");
		Date fromDate = new Date(System.currentTimeMillis()-15*24*60*60*1000);
		Date toDate = new Date(System.currentTimeMillis()+15*24*60*60*1000);
		try {
			fromDate = StringUtils.hasText(request.getParameter("fromDate"))?new SimpleDateFormat("M/d/yyyy", Locale.US).parse(request.getParameter("fromDate")):fromDate;
			toDate = StringUtils.hasText(request.getParameter("toDate"))?new SimpleDateFormat("M/d/yyyy", Locale.US).parse(request.getParameter("toDate")):toDate;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			map.put("success", new Boolean("false"));
			e.printStackTrace();
		}  

		logger.info(" +++++++ fromDate:"+fromDate);
		logger.info(" +++++++ toDate:"+toDate);
		
		String owner = request.getParameter("owner");
		List<ToDo> toDoList = toDoService.searchToDoList(owner, status, fromDate, toDate);
		 
		//  List<ToDo> toDoList = toDoService.getToDoList(owner, "open");
		 map.put("rows", toDoList);
		 
		 return map;
		 
	}
	

	
	@RequestMapping(value = "saveToDo.json", method = RequestMethod.POST)
	public Map create(@Valid ToDo toDo, BindingResult errors){

		Map<String, Object> map = new HashMap<String, Object>();
		
		if (errors.hasErrors()) {
			logger.info(" +++++++++in saveToDo.json+++ has errors ");
			
			//if using server side validation, the following code is needed
          List<FieldError> lerr = errors.getFieldErrors();
            for (FieldError err: lerr) {
            	
            	if("dueDate".equals(err.getField())){
            		// msg.append("Due Date must not be empty. And format must be mm/dd/yyyy.<br>");
            		map.put("msg", "Format must be MM/dd/yyyy.");
            	}else if("desc".equals(err.getField())){
            		map.put("msg", "Description must not be empty.");
            		// msg.append("Description must not be empty. <br>");
            	}else if("owner".equals(err.getField())){
            		map.put("msg", "Owner must not be empty.");
            		// msg.append("Owner must not be empty. <br>");
            	}else if("priority".equals(err.getField())){
            		map.put("msg", "Priority must not be empty.");
            		//msg.append("Priority must not be empty. <br>");
            	}
		       
				map.put("success", new Boolean("false"));
            } //end of for

		}else{
		
			toDo.setCreatedDate(new Date());
			toDo.setStatus("open");
			
			toDoService.saveToDo(toDo);	
			map.put("success", new Boolean("true"));
		}
		return map;
	}
	
	@RequestMapping(value = "removeToDo.json", method = RequestMethod.POST)
	public Map delete(@Valid ToDo toDo, BindingResult errors){
		
		logger.info(" +++++++++in removeToDo.json: id:"+ toDo.getId());

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			toDoService.deleteToDo(toDo);
		} catch (Exception e) {
			// TODO: handle exception
			map.put("success", new Boolean("false"));
			map.put("msg", "An error happened. The toDo is NOT removed.");
			return map;
		}
		map.put("success", new Boolean("true"));
		return map;
	}
	
	@RequestMapping(value = "updateToDo.json", method = RequestMethod.POST)
	public Map update(@Valid ToDo toDo, BindingResult errors){
		
		toDo.setCreatedDate(new Date());
		toDo.setStatus("open");
		if(toDo.getOrderId()==null){
			toDo.setOrderId("");
		}
		logger.info(" +++++++++in updateToDo.json: id:"+ toDo.getId());
		logger.info(" +++++++++in updateToDo.json: orderId:"+ toDo.getOrderId());
		logger.info(" +++++++++in updateToDo.json: owner:"+ toDo.getOwner());
		logger.info(" +++++++++in updateToDo.json: dueDate:"+ toDo.getDueDate());
		logger.info(" +++++++++in updateToDo.json: priority:"+ toDo.getPriority());
		logger.info(" +++++++++in updateToDo.json: createdDate:"+ toDo.getCreatedDate());
		logger.info(" +++++++++in updateToDo.json: desc:"+ toDo.getDesc());
				
		Map<String, Object> map = new HashMap<String, Object>();
		toDoService.updateToDo(toDo);
		
		map.put("success", new Boolean("true"));
		return map;
	}
	
	
	@RequestMapping(value = "finishToDo.json", method = RequestMethod.POST)
	public Map finishToDo(@Valid ToDo toDo, BindingResult errors){
		
		logger.info(" +++++++++in removeToDo.json: id:"+ toDo.getId());

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			toDoService.finishToDo(toDo);
		} catch (Exception e) {
			// TODO: handle exception
			map.put("success", new Boolean("false"));
			map.put("msg", "An error happened. The toDo is NOT updated.");
			return map;
		}
		map.put("success", new Boolean("true"));
		return map;
	}

	@RequestMapping(value = "searchToDo.json", method = RequestMethod.POST)
	public Map searchToDo(HttpServletRequest request, HttpServletResponse response){
		
		logger.info(" +++++++++in searchToDo.json: status:"+ request.getParameter("status")+"|"+"owner:"+request.getParameter("owner")+"|"+request.getParameter("fromDate")+"|"+request.getParameter("toDate"));
		List toDoList;
		
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			toDoList = toDoService.searchToDoList("artist", "open", new Date("05/01/2012"), new Date("05/10/2012"));
		} catch (Exception e) {
			// TODO: handle exception
			map.put("success", new Boolean("false"));
			map.put("msg", "An error happened. The toDo is NOT updated.");
			return map;
		}
		map.put("rows", toDoList);
		map.put("success", new Boolean("true"));
		return map;
	}
	
}
